#!/bin/bash
# Usage
# [DEV=sdb1] ./mkmini.sh [-a]

update_sg2042() {
        echo "Updating SD-card for $SOC_TYPE......"

	if [ ! -f $UDISK/FLAG_MINIMAL ]; then
		echo "ERROR: not mininal sdcard, pleaes double-check!"
		return 1
	fi

	if [ "$1" == "-a" ]; then
		echo "Removing zsbl and sbi ......"
		sudo rm $UDISK/zsbl.bin
		sudo rm $UDISK/riscv64/fw_dynamic.bin
		echo "Removing Done!"

		echo "Copying zsbl and sbi to sd-card"
		sudo cp $OUT_ZSBL/zsbl.bin $UDISK/zsbl.bin
		sudo cp $OUT_SBI/platform/generic/firmware/fw_dynamic.bin $UDISK/riscv64/fw_dynamic.bin
		echo "Copying Done!"
	fi

	echo "Removing dtb and kernel ......"
	sudo rm $UDISK/riscv64/$DTB_FILE_SDCARD
	sudo rm $UDISK/riscv64/riscv64_Image
	echo "Removing Done!"

	echo "Copying dtb and kernel to sd-card"
	sudo cp $OUT_LINUX/arch/riscv/boot/dts/sophgo/$DTB_FILE $UDISK/riscv64/$DTB_FILE_SDCARD
	sudo cp $OUT_LINUX/arch/riscv/boot/Image $UDISK/riscv64/riscv64_Image
	echo "Copying Done!"
}

update_k230() {
        echo "Updating SD-card for $SOC_TYPE......"

	echo "Removing dtb and kernel ......"
	sudo rm -f $UDISK/$DTB_FILE_SDCARD
	sudo rm -f $UDISK/Image
	echo "Removing Done!"

	echo "Copying dtb and kernel to sd-card"
	sudo cp $OUT_LINUX/arch/riscv/boot/dts/canaan/$DTB_FILE $UDISK/$DTB_FILE_SDCARD
	sudo cp $OUT_LINUX/arch/riscv/boot/Image $UDISK/Image
	echo "Copying Done!"
}

source ./envsetup

if [[ -z "${DEV}" ]]; then
	DEV=sdb1
fi

UDISK=$WS/u-disk
#echo "UDISK=$UDISK"

OUT_ZSBL=$WS_LINUX/out-zsbl
OUT_SBI=$WS_LINUX/out-sbi
OUT_LINUX=$WS_LINUX/out-$SOC_TYPE
#echo "OUT_ZSBL=$OUT_ZSBL"
#echo "OUT_SBI=$OUT_SBI"
#echo "OUT_LINUX=$OUT_LINUX"

print_env

echo "-------------------"
echo "DEV=$DEV"
echo "==================="


read -p "Would you continue? [N/y]:" choice
case $choice in
Y | y)
	echo "======> Continue ......"
	;;
*)
	echo "======> Cancelled ...... Quitting now."
	exit
	;;
esac

sudo umount $UDISK
sudo mount /dev/$DEV $UDISK
if [ $? -ne 0 ]; then
	echo "ERROR: mount failed"
	exit 1
fi
echo "Mounted /dev/$DEV on $UDISK ......"

update_$SOC_TYPE $1

sudo umount $UDISK

echo "Done!"

